package cn.dankal.flyaudio.personal.setting;

import android.content.ContentResolver;
import android.content.Context;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.dankal.basiclib.util.FileUtils;
import cn.dankal.basiclib.util.StringUtil;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.basiclib.util.image.PicUtils;
import cn.dankal.flyaudio.R;

/**
 * @author vane
 * @since 2018/8/8
 */

public class FeedbackPicAdapter extends RecyclerView.Adapter<FeedbackPicAdapter.FeedbackViewHolder> {

    private Context mContext;
    private int type = 1;//1代表图片 2代表视频
    private List<Uri> uris = new ArrayList<>();
    private OnAddPicClickListener mOnAddPicClickListener;

    public FeedbackPicAdapter(Context context, OnAddPicClickListener onAddPicClickListener) {
        mContext = context;
        mOnAddPicClickListener = onAddPicClickListener;
        //获取 ic_add_picture 的uri
        String scheme = ContentResolver.SCHEME_ANDROID_RESOURCE + "://";
        String packageName = context.getResources().getResourcePackageName(R.mipmap.ic_moment_add) + "/";
        String typeName = context.getResources().getResourceTypeName(R.mipmap.ic_moment_add) + "/";
        String entryName = context.getResources().getResourceEntryName(R.mipmap.ic_moment_add);
        String uriString = scheme + packageName + typeName + entryName;
        Uri uri = Uri.parse(uriString);
        uris.add(uri);
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    /**
     * 添加图片uri
     */
    public void add(Uri uri) {
        try {
            uris.add(uris.size() - 1, uri);
            notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addALL(List<Uri> uri) {
        try {
            uris.addAll(uris.size() - 1, uri);
            notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addALLVideo(List<Uri> uri) {
        try {
            uris.clear();
            String scheme = ContentResolver.SCHEME_ANDROID_RESOURCE + "://";
            String packageName = mContext.getResources().getResourcePackageName(R.mipmap.ic_moment_add) + "/";
            String typeName = mContext.getResources().getResourceTypeName(R.mipmap.ic_moment_add) + "/";
            String entryName = mContext.getResources().getResourceEntryName(R.mipmap.ic_moment_add);
            String uriString = scheme + packageName + typeName + entryName;
            Uri uri1 = Uri.parse(uriString);
            uris.add(uri1);
            uris.addAll(uris.size() - 1, uri);
            notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @NonNull
    @Override
    public FeedbackViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.rv_item_feedback_pic, parent, false);
        return new FeedbackViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull FeedbackViewHolder holder, int position) {
        Uri uri = uris.get(position);
        if (uri == null) {
            return;
        }
        boolean isAddPhoto = ContentResolver.SCHEME_ANDROID_RESOURCE.equals(uri.getScheme());
        holder.ivPhotoDelete.setVisibility(isAddPhoto ? View.GONE : View.VISIBLE);

        Glide.with(mContext)
                .asBitmap() // some .jpeg files are actually gif
                .load(uri)
                .apply(new RequestOptions()
                        .centerCrop()
                        .disallowHardwareConfig())
                .into(holder.ivPhoto);

        //PicUtils.loadNormal(StringUtil.safeString(uri), holder.ivPhoto);
        //Glide.with(mContext).load(uri).into(holder.ivPhoto);

        holder.ivPhotoDelete.setOnClickListener(v -> showConfirmDelete(position));

        holder.ivPhoto.setOnClickListener(v -> {
            Uri uri1 = uris.get(position);
            if (uri1 == null) {
                return;
            }
            boolean isAddPhoto1 = ContentResolver.SCHEME_ANDROID_RESOURCE.equals(uri1.getScheme());
            if (isAddPhoto1 && mOnAddPicClickListener != null) {
                mOnAddPicClickListener.addPhoto();
            }
        });
    }

    @Override
    public int getItemCount() {
        return getType() == 1 ? (uris.size() > 9 ? 9 : uris.size()) : 1;
    }


    private void showConfirmDelete(int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("删除")
                .setMessage("确定删除吗？")
                .setPositiveButton("是", (dialogInterface, i) -> {
                    if (FileUtils.deleteFile(uris.get(position).getPath())) {
                        uris.remove(position);
                        notifyItemRemoved(position);
                        notifyDataSetChanged();
                        if (mOnAddPicClickListener != null) {
                            mOnAddPicClickListener.deletePhoto(position);
                        }
                    } else {
                        ToastUtils.showShort("删除失败");
                    }
                    dialogInterface.dismiss();
                })
                .setNegativeButton("否", (dialogInterface, i) -> dialogInterface.dismiss()).create().show();
    }

    class FeedbackViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.iv_photo)
        ImageView ivPhoto;
        @BindView(R.id.iv_photo_delete)
        ImageView ivPhotoDelete;

        public FeedbackViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }


    public interface OnAddPicClickListener {
        /**
         * 添加图片
         */
        void addPhoto();

        /**
         * 删除图片
         */
        void deletePhoto(int pos);
    }
}
